
PLUG.Platform = PLUG_PLATFORM_CLIENT

PLUG.ClassName = "cl_hud"
PLUG.PrintName = "Clientside HUD"
PLUG.Author = "thomasfn"

PLUG.ViewRange = 2048

function PLUG:AddHooks()
	plugs.Hook( PLUG_PLATFORM_CLIENT, "HUDPaint" )
end

local yoffset = Vector( 0, 0, 48 )
function PLUG:HUDPaint()
	local tr = LocalPlayer():GetEyeTrace()
	local ent = tr.Entity
	if (ent && ent:IsValid() && ent:IsPlayer()) then
		local p = (ent:GetPos() + yoffset):ToScreen()
		self:DrawPlayerLabel( ent, p.x, p.y )
	end
end

local bgcol = Color( 60, 60, 60 )
local t = {}
function PLUG:DrawPlayerLabel( ply, x, y )
	t[1] = ply:Nick()
	t[2] = ply:GetNWString( "usergroup" )
	local grp = ply:UsergroupTable()
	local col = bgcol
	if (grp && grp.Colour) then col = grp.Colour end
	self:DrawLabel( x, y, t, "ScoreboardText", col, color_white, 4 )
end

local function GetMax( tbl )
	if (!tbl) || (#tbl == 0) then return 0 end
	local c = tbl[1]
	for k, v in pairs( tbl ) do
		if (v > c) then c = v end
	end
	return c
end

local function GetMin( tbl )
	if (!tbl) || (#tbl == 0) then return 0 end
	local c = tbl[1]
	for k, v in pairs( tbl ) do
		if (v < c) then c = v end
	end
	return c
end

function PLUG:DrawLabel( x, y, txt, font, bgcol, textcol, padding )
	if (type( txt ) != "table") then txt = { txt } end
	if (#txt == 0) then return end
	local tmp = {}
	surface.SetFont( font )
	local ch = 0
	local tth = 0
	for k, v in pairs( txt ) do
		local tw, th = surface.GetTextSize( v )
		table.insert( tmp, tw )
		ch = ch + th
		tth = th
	end
	local cw = GetMax( tmp ) + padding
	local ypos = y-(ch*0.5)
	draw.RoundedBox( 6, x-(cw*0.5), ypos, cw, ch, bgcol )
	local cnt
	for cnt=1, #txt do
		draw.SimpleText( txt[ cnt ], font, x, ypos + (cnt-0.5)*tth, textcol, 1, 1 )
	end
end